import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import api from '../api/axiosConfig'; // 修正 #1: 导入我们刚创建的 api 实例
import axios from 'axios'; // 修正 #3: 导入 axios 以使用其错误类型检查

const RegisterPage = () => {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    if (password !== confirmPassword) {
      setError('两次输入的密码不一致。');
      return;
    }

    try {
      // 修正 #2: 这里是干净的 api.post 调用
      await api.post('/users/register', {
        username,
        email,
        password,
      });

      setSuccess('注册成功！现在您可以登录了。');
      
      setTimeout(() => {
        navigate('/login');
      }, 2000);

    } catch (err) {
      // 修正 #3: 使用更安全的错误处理，替换 (err: any)
      if (axios.isAxiosError(err)) {
        setError(err.response?.data?.message || '注册失败，请稍后再试。');
      } else {
        setError('发生了一个未知错误。');
      }
      console.error(err);
    }
  };

  return (
    <div>
      <h2>注册新账号</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label>用户名:</label>
          <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} required />
        </div>
        <div>
          <label>邮箱:</label>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
        </div>
        <div>
          <label>密码:</label>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
        </div>
        <div>
          <label>确认密码:</label>
          <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} required />
        </div>

        {error && <p style={{ color: 'red' }}>{error}</p>}
        {success && <p style={{ color: 'green' }}>{success}</p>}
        
        <button type="submit">注册</button>
      </form>
      <p>
        已经有账号了？ <Link to="/login">点此登录</Link>
      </p>
    </div>
  );
};

export default RegisterPage;